package cn.edu.buaa.treehole.controller.get;

import cn.edu.buaa.treehole.service.TimeService;
import cn.edu.buaa.treehole.dao.exception.DaoException;
import cn.edu.buaa.treehole.dao.exception.PidNotExistException;
import cn.edu.buaa.treehole.pojo.fixedinfo.NamedReplyInfo;
import cn.edu.buaa.treehole.pojo.network.get.ReplyNetworkInfo;
import cn.edu.buaa.treehole.service.ReplyInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/*
 * @author Deng XinYu
 * */
@Controller
@RequestMapping("reply_info")
public class ReplyInfoController {
    private final ReplyInfoService replyInfoService;
    private final TimeService timeService;
    private final Logger logger = LoggerFactory.getLogger(ReplyInfoController.class);

    @Autowired
    public ReplyInfoController(ReplyInfoService replyInfoService, TimeService timeService) {
        this.replyInfoService = replyInfoService;
        this.timeService = timeService;
    }

    @Override
    public String toString() {
        return "ReplyInfoController{" +
                "replyInfoService=" + replyInfoService +
                '}';
    }

    @RequestMapping("/{pid}/{rid}")
    @ResponseBody
    public ReplyNetworkInfo getInfo(
            @PathVariable long pid,
            @PathVariable long rid
    ) {
        ReplyNetworkInfo out = new ReplyNetworkInfo();

        try {
            NamedReplyInfo info = replyInfoService.getReplyInfo(pid, rid);
            if (info.getPid() != pid || info.getRid() != rid) {
                throw new DaoException(toString() +
                        " using pid=" + pid +
                        ", rid=" + rid +
                        ", but get " + info);
            }
            out.setRid(info.getRid());
            out.setContent(info.getContent());
            out.setTime(timeService.format(info.getDate()));
            out.setName(info.getName());
            out.setStatus("success");
        }
        catch (PidNotExistException e) {
            out.setStatus("null");
        }
        catch (Exception e) {
            logger.error("getInfo()", e);
            out.setStatus("exception");
        }

        return out;
    }
}
